/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package desu.nya.DAO;

import desu.db.HibernateUtil;
import desu.nya.Anime;
import desu.nya.Otaku;
import desu.nya.Rating;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.AvgProjection;
import org.hibernate.criterion.Projections;

/**
 *
 * @author Fess
 */
public class RatingIMPL implements RatingDAO{

    @Override
    public Rating vote(Rating rating) throws SQLException {
        Session session=null;
        try{
            session=HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.save(rating);
            session.getTransaction().commit();
        }
        catch(Exception ex){
            System.err.println("HiB: Anime insert error");
        }
        finally{
            if(session!=null&&session.isOpen())
                session.close();
        }
        return rating;
    }

    @Override
    public Rating getRatingByID(int id) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Rating> getRateByNick(Otaku otaku) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Rating> getRateByAnime(Anime anime) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Rating getRateByNickAndAnime(Otaku otaku, Anime anime) throws SQLException {
        Session session=null;
        avgRateRefresh(anime);
        Rating rating=null;
        List<Rating> rList;
        try{
            session=HibernateUtil.getSessionFactory().openSession();
            Criteria cr=session.createCriteria(Rating.class);
            rList=cr.add(Expression.eq("anime", anime)).add(Expression.eq("otaku", otaku)).list();
            if(rList==null){
                System.err.println("Rating not found");
                return null;
            }
            rating=rList.get(0);
        }
        catch(Exception ex){
            System.err.println("Ошибка при получении студии");
        }
        finally{
            if(session!=null&&session.isOpen())
                session.close();
        }    
        return rating;
    }

    @Override
    public void updateRating(Long rating_id, Rating rating) throws SQLException {
        Session session=null;
        double avg;
        try{
            session=HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Criteria cr=session.createCriteria(Rating.class);
            Anime anime=rating.getAnime();
            cr.add(Expression.eq("anime", anime)).setProjection(Projections.avg("rate"));
            if(rating.getId()==null)
                session.save(rating);
            else
                session.update(rating);
            session.update(anime);
            session.getTransaction().commit();
            session.beginTransaction();
            List list=cr.list();
            if(list!=null&&!list.isEmpty()&&list.get(0)!=null)
                avg=(Double)cr.list().get(0);
            else
                avg=rating.getRate();
            anime.setAvgRate(avg);
            session.update(anime);
            session.getTransaction().commit();

        }
        catch(Exception ex){
            System.err.println("HiB: Rating update fail");
        }
        finally{
            if(session!=null&&session.isOpen())
                session.close();
        }
    }

    @Override
    public List<Rating> getAllRating() throws SQLException {
        Session session=null;
        List<Rating> list=null;
        try{
            session=HibernateUtil.getSessionFactory().openSession();
            list=session.createCriteria(Rating.class).list();
        }
        catch(Exception ex){
            System.err.println("HiB: Genre List getting error");
        }
        finally{
            if(session!=null&&session.isOpen())
                session.close();
        }
        return list;
    }

    @Override
    public void deleteRating(Rating rating) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    private void avgRateRefresh(Anime anime){
        Session session=null;
        try{
            session=HibernateUtil.getSessionFactory().openSession();
            Criteria cr=session.createCriteria(Rating.class);
            cr.add(Expression.eq("anime", anime)).setProjection(Projections.avg("rate"));
            int s=(Integer)cr.list().get(0);
            session.beginTransaction();
//            session.update(rating);
            session.getTransaction().commit();
        }
        catch(Exception ex){
            System.err.println("HiB: Rating update fail");
        }
        finally{
            if(session!=null&&session.isOpen())
                session.close();
        }
    }
    
}
